<?php
/**
 * 国内库存
 * (model)
 */
namespace App\Models\Inventory;

use App\Models\Basics\SysArea;
use App\Models\Basics\SysIArea;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Util\User;
use Illuminate\Database\Eloquent\Model;
class AreaCn extends Model
{
    protected $table = 'inventory_cn';

    protected $guarded = [];

    public $timestamps = false;

    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    public function iArea(){
        return $this->belongsTo(SysIArea::class,'area_id','area_id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public static function getDownloadData($re){
        $user = [];
        foreach ($re as $row){
            $temp = [];
            $temp['area'] = $row->area->area ?? '';
            $temp['psku_code'] = $row->sku->psku_code ?? '';
            $temp['season'] = ProductClassify::$_season[$row->sku->classify->season ?? 3];
            $temp['classify'] = $row->sku->classify->title ?? '';
            if(!array_key_exists($row->iArea->muser_id ?? '',$user)){
                $user[$row->iArea->muser_id ?? ''] = User::getUsernameById($row->iArea->muser_id ?? '');
            }
            $temp['muser'] = $user[$row->iArea->muser_id ?? ''];
            $temp['instant'] = $row->instant;
            $temp['area_transit'] = $row->area_transit;
            $temp['reserve'] = $row->reserve;
            $temp['psku_cn'] = $row->sku->psku_cn ?? '';
            yield $temp;
        }
    }

    public static function getAreaCn($areaId,$pSkuId){
        return self::query()
            ->where('area_id', $areaId)
            ->where('psku_id',$pSkuId)
            ->first();
    }

    public static function getInstant($areaId,$pSkuId){
         $instant = self::query()
             ->where('area_id', $areaId)
            ->where('psku_id',$pSkuId)
            ->value('instant');
        return $instant ?: 0;
    }

    public static function getTransit($areaId,$pSkuId){
        $transit = self::query()
            ->where('area_id', $areaId)
            ->where('psku_id',$pSkuId)
            ->value('area_transit');
        return $transit ?: 0;
    }

    public static function getReserve($areaId,$pSkuId){
        $reserve = self::query()
            ->where('area_id', $areaId)
            ->where('psku_id',$pSkuId)
            ->value('reserve');
        return $reserve ?: 0;
    }

    public static function addAreaCn($areaId,$pSkuId){
        $count = AreaCn::query()
            ->where('area_id', $areaId)
            ->where('psku_id',$pSkuId)
            ->count();
        if($count == 0){
            AreaCn::query()->create(['area_id' => $areaId,'psku_id' => $pSkuId]);
        }
    }

    /**
     * 验证JP-国内库存 （rakuten自动发货）
     * @param array $areaId
     * @param int $pSkuId
     * @param int $platId
     * @param int $accountId
     * @return int|mixed
     */
    public static function getInstantMax($areaId = [], $pSkuId = 0, $platId = 0, $accountId = 0){
        $query = self::query();
        if ($areaId) $query->whereIn('area_id', $areaId);
        if ($pSkuId > 0) $query->where('psku_id', $pSkuId);
        if ($platId > 0) $query->where('plat_id', $platId);
        if ($accountId > 0) $query->where('account_id', $accountId);

        $instant = $query->max('instant');
        return $instant ?: 0;
    }

    /**
     * JP-国内在库（模型）
     * @param array $areaId
     * @param int $pSkuId
     * @param int $platId
     * @param int $accountId
     * @param string $str
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getInstantMaxFind($areaId = [], $pSkuId = 0, $platId = 0, $accountId = 0, $str = 'instant'){
        $query = self::query();
        if ($areaId) $query->whereIn('area_id', $areaId);
        if ($pSkuId > 0) $query->where('psku_id', $pSkuId);
        if ($platId > 0) $query->where('plat_id', $platId);
        if ($accountId > 0) $query->where('account_id', $accountId);

        $query->orderByDesc('instant');
        return $query->lockForUpdate()->first();
    }

    /**
     * 验证JP-国内库存 (验证国内库存)
     * @param $rakutenOrder
     * @param $rakutenOrder
     * @return bool
     */
    public static function _checkCnInventoryFnsku($rakutenOrder){
        if (!$rakutenOrder) return false;

        $inventoryFlag = false;
        foreach ($rakutenOrder->rakuten_orders_items as $_k => $_v) {
            $pskuId = ProductSku::getValueByCode($_v->variant_id, 'id');
            if (!$pskuId){
                $inventoryFlag = false;
                break;
            }

            //库存不足,跳出循环,终止当前订单(整单)
            $fbaInstant = AreaCn::getInstantMax([SysArea::AREA_JP],$pskuId);
            if (intval($fbaInstant) < intval($_v->units)) {
                $inventoryFlag = false;
                break;
            }
            $inventoryFlag = true;
        }

        return $inventoryFlag;
    }

    /**
     * J更新P-国内库存 (扣减国内库存)
     * @param $rakutenOrder
     * @return bool
     */
    public static function _saveCnInventoryFnsku($rakutenOrder){
        if (!$rakutenOrder) return false;

        $inventoryFlag = false;
        foreach ($rakutenOrder->rakuten_orders_items as $_k => $_v){
            $pskuId = ProductSku::getValueByCode($_v->variant_id, 'id');
            if (!$pskuId){
                $inventoryFlag = false;
                break;
            }

            //海外仓(代发)库存
            $cnInventory = AreaCn::getInstantMaxFind([SysArea::AREA_JP],$pskuId);
            if (!$cnInventory){
                $inventoryFlag = false;
                break;
            }
            if (intval($cnInventory->instant) < intval($_v->units)){
                $inventoryFlag = false;
                break;
            }
            $cnInventory->instant -= intval($_v->units); //扣减在库
            $flag = $cnInventory->save();
            if (!$flag){
                $inventoryFlag = false;
                break;
            }

            $inventoryFlag = true;
        }

        return $inventoryFlag;
    }


}
